package com.xm.service.realm;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xm.dao.UserDao;
import com.xm.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    UserDao userDao;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username=(String) principals.getPrimaryPrincipal();
        User user=userDao.selectOne(new QueryWrapper<>(new User().setUsername(username)));
        Set<String> set=userDao.selectPermissionById(user.getId());
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setStringPermissions(set);
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username=((UsernamePasswordToken)token).getUsername();
        User user=new User();
        user.setUsername(username);
        user=userDao.selectOne(new QueryWrapper<>(user));
        if(user ==null)throw new UnknownAccountException();
        if(user.getValid()==0)throw new LockedAccountException();
        ByteSource byteSource=new ByteSource.Util().bytes(user.getSalt());
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user.getUsername(),
                user.getPassword(), byteSource,this.getName());
        return info;
    }

    @Override
    public CredentialsMatcher getCredentialsMatcher(){
        HashedCredentialsMatcher matcher=new HashedCredentialsMatcher();
        matcher.setHashIterations(1);
        matcher.setHashAlgorithmName("MD5");
        return matcher;

    }

}
